// 引入样式
require("../../assets/css/common.css");
require("../../assets/font_44fp3ls0tzq/iconfont.css");
require("../../assets/css/reset.css");
require("../../assets/css/normalize.css");
require("./login.css");

// 引入模块
const CaptchaMini = require("captcha-mini");
const axios = require("axios");
const dom = require("../../utils/dom.js");

document.addEventListener("DOMContentLoaded", function () {
	// 创建验证码
	let captcha = new CaptchaMini();
	let condeInit = "";
	captcha.draw(dom.get("#captcha"), (r) => {
		// 验证码转换为小写
		condeInit = r.toLowerCase();
	});

	// 点击注册账号，进行验证
	dom.get("#reg-btn").addEventListener("click", function () {
		let error = dom.get("#error");
		// 手机号验证
		let tel = dom.get("#tel").value;
		let reg = /^1[34567]\d{9}$/i;
		if (reg.test(tel)) {
			error.textContent = "";
		} else {
			error.textContent = "手机格式有误";
			return;
		}

		// 验证码验证
		let code = dom.get("#code").value.toLowerCase();
		if (condeInit === code) {
			error.textContent = "";
		} else {
			error.textContent = "验证码有误";
			return;
		}

		// 密码验证
		let pwd1 = dom.get("#pwd1").value;
		let reg1 = /^\w{6,12}$/i;
		if (reg1.test(pwd1)) {
			error.textContent = "";
		} else {
			error.textContent = "密码输入有误";
			return;
		}
		// 再次密码验证
		let pwd2 = dom.get("#pwd2").value;
		if (pwd1 === pwd2) {
			error.textContent = "";
		} else {
			error.textContent = "再次密码输入有误";
			return;
		}
		// 到达这步，前端验证成功；进行后端验证
		axios
			.post("http://fitness.h5.itsource.cn:3701/api/user/register", {
				account: tel,
				password: pwd1,
			})
			.then(function (res) {
				if (res.data.errno === 0) {
					location.href = "register.html";
				} else {
					error.textContent = res.data.message;
				}
			});
	});
});
